import numpy as np
import matplotlib.pyplot as plt

# 定义激活函数
def relu(x):
    return np.maximum(0, x)

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def tanh(x):
    return np.tanh(x)

# 生成输入数据
x = np.linspace(-5, 5, 100)

# 计算激活函数的输出
y_relu = relu(x)
y_sigmoid = sigmoid(x)
y_tanh = tanh(x)

# 绘制图像
plt.figure(figsize=(12, 4))

# ReLU
plt.subplot(1, 3, 1)
plt.plot(x, y_relu, label='ReLU', color='blue')
plt.title('ReLU')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.legend()

# Sigmoid
plt.subplot(1, 3, 2)
plt.plot(x, y_sigmoid, label='Sigmoid', color='green')
plt.title('Sigmoid')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.legend()

# Tanh
plt.subplot(1, 3, 3)
plt.plot(x, y_tanh, label='Tanh', color='red')
plt.title('Tanh')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.legend()

# 调整布局
plt.tight_layout()
plt.show()